package screen;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import weibo.Timeline;
import weibo.Users;
import weibo.http.AccessToken;
import weibo.model.Status;
import weibo.model.StatusWapper;
import weibo.model.User;
import weibo.model.WeiboException;
import code.Function;
import ctrl.ForegroundManager;
import ctrl.ListStyleButtonSet;
import ctrl.MyConnectionFactory;
import ctrl.StatusesListStyleButtonField;
import ctrl.UserInforListStyleButtonField;

public class ShowStatusesScreen extends MainScreen
{
	AccessToken _accessToken;
	String _uid;
	User _user;
	
	VerticalFieldManager _readMoreGround=new VerticalFieldManager();
	ForegroundManager _foreground=new ForegroundManager(0);
	ListStyleButtonSet _buttonSet=new ListStyleButtonSet();
	StatusesListStyleButtonField _link;
	Status retweet_status=null;
	StatusWapper statuses;
	byte[] avatarData=null;
	Status status;
	int currentPage=1;
	
    ConnectionThread _connectionThread = new ConnectionThread();
    
	/**
	 * 显示已登录用户微博列表窗口
	 * @param accessToken 令牌类
	 */
	public ShowStatusesScreen(AccessToken accessToken)
	{
		this(accessToken, accessToken.getUID());
	}
	
	/**
	 * 显示用户微博列表窗口
	 * @param accessToken 令牌类
	 * @param _uid 用户id
	 */
	public ShowStatusesScreen(AccessToken accessToken, String uid)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT);
		
        if(!_connectionThread.isStarted()) {_connectionThread.start();}
        
		_accessToken=accessToken;
		_uid=uid;
		
		Users user=new Users(_accessToken.getToken());
		User me=null;
		try {
			me=user.showUserById(_uid);
		} catch (WeiboException e1) {}
		
		HorizontalFieldManager hfm=new HorizontalFieldManager(FIELD_HCENTER);
		hfm.add(new LabelField(me.getScreenName()+"的微博列表"));
		setTitle(hfm);

		_buttonSet.add(new LabelField("Please wait....", USE_ALL_WIDTH));
		_readMoreGround.add(_buttonSet);
		
		add(_foreground);

		_connectionThread.fetch();
	}
	
	public ShowStatusesScreen(AccessToken accessToken, User user)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT);
		
        if(!_connectionThread.isStarted()) {_connectionThread.start();}
        
		_accessToken=accessToken;
		_uid=user.getId();
		_user=user;
		
		HorizontalFieldManager hfm=new HorizontalFieldManager(FIELD_HCENTER);
		hfm.add(new LabelField(_user.getScreenName()+"的微博列表"));
		setTitle(hfm);

		_buttonSet.add(new LabelField("Please wait....", USE_ALL_WIDTH));
		_foreground.add(_buttonSet);
		
		add(_foreground);

		_connectionThread.fetch();
	}
		
    protected boolean keyChar(char key, int status, int time)
    {
    	if(key==Characters.LATIN_CAPITAL_LETTER_P || key==Characters.LATIN_SMALL_LETTER_P)
    	{
    		Function.errorDialog(Thread.activeCount()-1+"");
    		return true;
    	}
    	
    	return super.keyChar(key, status, time);
    }

	public boolean onClose()
	{
		_connectionThread.stop();
		
		return super.onClose();
	}
	
	class ConnectionThread extends Thread
    {
        private static final int TIMEOUT = 1000;
        private volatile boolean _fetchStarted = false;
        private volatile boolean _stop = false;

        private String getAccessToken() {return _accessToken.getToken();}
        private boolean isStarted() {return _fetchStarted;}            
        private void fetch() {_fetchStarted = true;}
        private void stop() {_stop = true;}

        public void run()
        {
            for(;;)
            {
                while( !_fetchStarted && !_stop)  
                {
                    try {sleep(TIMEOUT);} catch (InterruptedException e) {Function.errorDialog("Thread#sleep threw " + e.toString());}
                }
                
                if(_stop) {return;}

                Timeline tm=new Timeline(getAccessToken());
				try {
					statuses=tm.getUserTimelineByUid(_uid, currentPage, 20);

					synchronized (Application.getEventLock())
					{
						Application.getApplication().invokeLater(new Runnable()
						{
							public void run()
							{
								Field child=_buttonSet.getField(_buttonSet.getFieldCount()-1);
								if(child instanceof UserInforListStyleButtonField)
								{
									_buttonSet.delete(child);
								}
								
								for(int i=0; i<statuses.getStatuses().size(); i++)
								{
									status=(Status) statuses.getStatuses().elementAt(i);
									_link=new StatusesListStyleButtonField(status);
									final Status currentStatus=status;
									_link.setChangeListener(new FieldChangeListener()
									{
										public void fieldChanged(Field field, int context)
										{
											UiApplication.getUiApplication().pushScreen(new ShowStatusScreen(_accessToken, currentStatus));
										}
									});
									_buttonSet.add(_link);
								}
								
								UserInforListStyleButtonField _more=new UserInforListStyleButtonField("加载更多微博内容", null, null);
								_more.setChangeListener(new FieldChangeListener()
								{
									public void fieldChanged(Field field, int context)
									{
										if(context!=FieldChangeListener.PROGRAMMATIC)
										{
											//Function.errorDialog("current page: " + currentPage);
											currentPage+=1;
											_connectionThread=new ConnectionThread();
											_connectionThread.start();
											_connectionThread.fetch();
										}
									}
								});
								_buttonSet.add(_more);
							}
						});
					}
					
					UiApplication.getUiApplication().invokeLater(new Runnable()
					{
						public void run()
						{
							if(_buttonSet.getField(0) instanceof LabelField) {_buttonSet.delete(_buttonSet.getField(0));}
							if(statuses.getStatuses().size()==0) {UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());}
						}
					});
					
					ConnectionThreadImage imageThread=new ConnectionThreadImage();
					imageThread.start();
					imageThread.fetch(statuses);
					
	                _fetchStarted = false;           
	                stop();
				} catch (WeiboException e) {Function.errorDialog(e.toString());}
            }
        }
    }
	
	private class ConnectionThreadImage extends Thread
    {
        private static final int TIMEOUT = 500;
        private byte[] data;
        private StatusWapper _statuses;
        
        private volatile boolean _fetchStarted = false;
        private volatile boolean _stop = false;

        private void fetch(StatusWapper statuses)
        {
        	_fetchStarted=true;
        	_statuses=statuses;
        }

        private void stop() {_stop = true;}

        public void run()
        {
            for(;;)
            {
                while(!_fetchStarted && !_stop)  
                {
                    try {sleep(TIMEOUT);} catch (InterruptedException e) {Function.errorDialog(StatusesListStyleButtonField.class.getName() + "\n\n" + "Thread#sleep threw " + e.toString());}
                }
                
                if(_stop) {return;}

                Status status=null;
                MyConnectionFactory factory=null;
                ConnectionDescriptor descriptor=null;
                HttpConnection httpConnection=null;
                InputStream inputStream=null;
                
                for(int i=0; i<_statuses.getStatuses().size(); i++)
                {
                	status=(Status) _statuses.getStatuses().elementAt(i);
                	String avatars=status.getUser().getProfileImageUrl();
                	String[] image_status=status.getThumbnailImages();
                	String[] image_retweet = null;
                	Status retweet=status.getRetweetedStatus();
                	if(retweet!=null)
                	{
                		if(!retweet.isDeleted())
                		{
                			image_retweet=retweet.getThumbnailImages();
                		}
                	}
                	
                    factory=new MyConnectionFactory();
                    descriptor=factory.getConnection(avatars);

                    if(descriptor==null)
                    {
                    	_fetchStarted=false;
                    	stop();
                    	return;
                    }
                    
                    httpConnection=(HttpConnection) descriptor.getConnection();
                    
                    try
                    {
    					inputStream=httpConnection.openInputStream();
    					
    					if(inputStream.available()>0)
    					{
    						data=IOUtilities.streamToBytes(inputStream);

    						if(data.length==httpConnection.getLength())
    						{
    							final int index=i+currentPage*20-20;
    							synchronized(Application.getEventLock())
    							{
    								Application.getApplication().invokeLater(new Runnable()
    								{
    									public void run()
    									{
    										StatusesListStyleButtonField link=(StatusesListStyleButtonField) _buttonSet.getField(index);
    										link.setAvatarIcon(data);
    									}
    								});
    							}
    						}
    					}
                    } catch (IOException e) {
                    //} finally {
                    //	if(inputStream!=null) {try {inputStream.close();} catch (Exception e2) {}}
                    //	if(httpConnection!=null) {try {httpConnection.close();} catch (Exception e2) {}}
                    }
                    
                    if(image_status!=null)
                    {
                    	descriptor=factory.getConnection(image_status[0]);
                    	
                        if(descriptor==null)
                        {
                        	_fetchStarted=false;
                        	stop();
                        	return;
                        }
                        
                        httpConnection=(HttpConnection) descriptor.getConnection();
                        
                        try
                        {
        					inputStream=httpConnection.openInputStream();
        					
        					if(inputStream.available()>0)
        					{
        						data=IOUtilities.streamToBytes(inputStream);

        						if(data.length==httpConnection.getLength())
        						{
        							final int index=i+currentPage*20-20;
        							synchronized(Application.getEventLock())
        							{
        								Application.getApplication().invokeLater(new Runnable()
        								{
        									public void run()
        									{
        										StatusesListStyleButtonField link=(StatusesListStyleButtonField) _buttonSet.getField(index);
        										link.setStatusImage(data);
        									}
        								});
        							}
        						}
        					}
                        } catch (IOException e) {}
                    }
                    
                    if(image_retweet!=null)
                    {
                    	descriptor=factory.getConnection(image_retweet[0]);
                    	
                        if(descriptor==null)
                        {
                        	_fetchStarted=false;
                        	stop();
                        	return;
                        }
                        
                        httpConnection=(HttpConnection) descriptor.getConnection();
                        
                        try
                        {
        					inputStream=httpConnection.openInputStream();
        					
        					if(inputStream.available()>0)
        					{
        						data=IOUtilities.streamToBytes(inputStream);

        						if(data.length==httpConnection.getLength())
        						{
        							final int index=i+currentPage*20-20;
        							synchronized(Application.getEventLock())
        							{
        								Application.getApplication().invokeLater(new Runnable()
        								{
        									public void run()
        									{
        										StatusesListStyleButtonField link=(StatusesListStyleButtonField) _buttonSet.getField(index);
        										link.setRetweetImage(data);
        									}
        								});
        							}
        						}
        					}
                        } catch (IOException e) {}
                    }
                }
                
                if(inputStream!=null) {try {inputStream.close();} catch (Exception e2) {}}
                if(httpConnection!=null) {try {httpConnection.close();} catch (Exception e2) {}}
                
                _fetchStarted = false;           
                stop();
            }
        }
    }
}